<?php

namespace backend\controllers;

use Yii;
use yii\db\Query;
use common\models\Product;
use common\models\ProductCategory;
use common\models\ProductSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;

/**
 * ProductController implements the CRUD actions for Product model.
 */
class ProductController extends AController
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

    /**
     * Lists all Product models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new ProductSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single Product model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new Product model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new Product();
        $pro_cate = new Query();

        if(!empty($_POST)){
            $pid = $_POST['Product']['category_name'];
            //处理产品参数
            $para = $_POST['Product']['parameter'];
            if($para){
                $array = explode(',,', $para);
                foreach ($array as $k => $v) {
                    if($v){
                        $last = explode('::', $v);
                        if($last[0]){
                            $list[$k][$last[0]] = $last[1];
                        }
                    }
                }
                if(isset($list)){
                    $_POST['Product']['parameter'] = json_encode($list);    
                }else{
                    $_POST['Product']['parameter'] = "";
                }
            }
        }
        if ($model->load($_POST/*Yii::$app->request->post()*/) && $model->save()) {
            //插入到产品分类表中
            for ($i=0;$i<count($pid);$i++) {
                $exist = ProductCategory::find()
                        ->where(['product_id'=>$model->id,'category_id'=>$pid[$i]])
                        ->asarray()
                        ->one();
                if(!$exist){
                    $pro_cate->createCommand()
                         ->Insert('product_category', ['product_id'=>$model->id,'category_id'=>$pid[$i]])
                         ->execute();
                }                        
            }
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Updates an existing Product model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        //ajax删除商品图片
        $del = Yii::$app->request->post('del');
        if(isset($del) && $del){
            $pro_pic_id = Yii::$app->request->post('id');
            $del_res =  (new Query())->createCommand()
                        ->Delete('product_gallery', ['id'=>$pro_pic_id])
                        ->execute();
            return $del_res;
        }

        $model = $this->findModel($id);

        $pro_cate = new Query();

        if(!empty($_POST)){
            $pid = $_POST['Product']['category_name'];
            //处理产品参数
            $para = $_POST['Product']['parameter'];
            if($para){
                $array = explode(',,', $para);
                foreach ($array as $k => $v) {
                    if($v){
                        $last = explode('::', $v);
                        if($last[0]){
                            $list[$k][$last[0]] = $last[1];
                        }
                    }
                }
                if(isset($list)){
                    $_POST['Product']['parameter'] = json_encode($list);    
                }else{
                    $_POST['Product']['parameter'] = "";
                }
            }
        }

        //查询当前商品的所有分类
        $current = ProductCategory::find()
                ->select('category_id')
                ->where(['product_id'=>$model->id])
                ->asarray()
                ->column();
        
        if ($model->load($_POST/*Yii::$app->request->post()*/) && $model->save()) {

            //比较当前选择的和已有分类的区别  删除取消勾选的项              
            $diff = array_diff($current, $pid);
            if($diff){
               foreach ($diff as $key => $value) {
                    $pro_cate->createCommand()
                             ->Delete('product_category', ['product_id'=>$model->id,'category_id'=>$value])
                             ->execute();
                }
            }
            //插入到产品分类表中
            for ($i=0;$i<count($pid);$i++) {
                $exist = ProductCategory::find()
                        ->where(['product_id'=>$model->id,'category_id'=>$pid[$i]])
                        ->asarray()
                        ->one();
                if(!$exist){
                    $pro_cate->createCommand()
                         ->Insert('product_category', ['product_id'=>$model->id,'category_id'=>$pid[$i]])
                         ->execute();
                }                        
            }
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('update', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Deletes an existing Product model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        //如果此商品删除成功，则删除其所有分类
        if($this->findModel($id)->delete()){
            $pro_cate = new Query();
            $pro_cate->createCommand()
                     ->Delete('product_category', ['product_id'=>$id])
                     ->execute();
        }

        return $this->redirect(['index']);
    }

    /**
     * Finds the Product model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return Product the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = Product::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
}
